package com.his.modules.sysjob.job;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.his.core.utils.HttpUtils;
import com.his.core.utils.StringUtils;
import com.his.modules.business.entity.CaSignDataLis;
import com.his.modules.business.service.CaSignDataLisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component("caSignDataLisBodyJob")
@Slf4j
public class CaSynSignDataLisBodyJob {
    @Autowired
    private CaSignDataLisService caSignDataService;
    /**
     * CA获取签名原文接口
     * @return
     */
    public void caSignDataLisBodyJob() {
        log.info("CA获取签名原文接口定时任务开始执行=================");
        QueryWrapper<CaSignDataLis> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("YWBODY");

        List<CaSignDataLis> caSignDataList = caSignDataService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(caSignDataList)) {
            log.info("CA获取Lis签名原文接口定时任务获取到未处理的业务数据条数：{}=================", caSignDataList.size());
            String returnStr = "";
            String url = "http://10.10.2.54/gateway/recipe/getSignInfo";
            for(CaSignDataLis ca : caSignDataList) {
                String params = "{\n" +
                        "    \"head\": {\n" +
                        "        \"clientId\": \"2020092910330581\", \n" +
                        "        \"clientSecret\": \"2020092910330570\"\n" +
                        "    }, \n" +
                        "    \"body\": {\n" +
                        "        \"uniqueId\": \"{{uniqueId}}\"\n" +
                        "    }\n" +
                        "}";

                params = params.replace("{{uniqueId}}", ca.getCaId());
                log.info("请求信息：url={}, param={}", url, params);
                returnStr = HttpUtils.doPost(url, params);
                log.info("请求信息：返回值={}", returnStr);
                if(StringUtils.isNotBlank(returnStr)) {
                    JSONObject jsonObject = new JSONObject(returnStr);
                    //获取成功
                    log.info("唯一值{}的签名原文为：{}", ca.getCaId(), jsonObject.getStr("signInfo"));
                    //更新业务状态及业务数据
                    ca.setYwbody(jsonObject.getStr("signInfo"));
                    caSignDataService.updateById(ca);
                }
            }
        }
    }
}